using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.FileManipulation
{
    public class FileLoopWorker:IWorker
    {
        private Thread _WorkerThread;
        private FileLoopInstruction _Instruction;
        private FileLoopOutput _Output;
        private Guid _TicketID;
        private RunContext _Context;
        private string _WorkflowName;
        private string _ComponentName;

        /// <summary>
        /// 
        /// </summary>
        public string ComponentName
        {
            get { return _ComponentName; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string WorkflowName
        {
            get { return _WorkflowName; }
        }

        public Thread WorkerThread
        {
            get { return _WorkerThread; }
        }

        public InstructionBase Instruction
        {
            get { return _Instruction; }
        }

        public ResultBase Output
        {
            get { return this._Output; }
        }

        public Type ComponentType
        {
            get { return typeof(FileEnumeatorComponent); }
        }

        public RunContext Context
        {
            get { return _Context; }
            set { _Context = value; }
        }

        public void SetInstruction(Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._TicketID = ticketGuid;
            this._Instruction = (FileLoopInstruction) request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        public void SetInstruction(RunContext context, Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._Context = context;
            this._TicketID = ticketGuid;
            this._Instruction = (FileLoopInstruction) request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        public void DoWork()
        {
            if(this.WorkerStartedEvent !=null)
            {
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = Thread.CurrentThread;
            this.GetFiles();
        }

        public void DoWorkAsync()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = new Thread(new ThreadStart(this.GetFiles));
            this._WorkerThread.Start();
        }

        public void CancelWork()
        {
            if (this._WorkerThread != null && this._WorkerThread.IsAlive)
            {
                this._WorkerThread.Abort();
                if (this.WorkerCancelledEvent != null)
                {
                    this.WorkerCancelledEvent(this._TicketID, this.GetType(), this._Instruction);
                }
            }
        }

        public event WorkerStarted WorkerStartedEvent;
        public event WorkerFinished WorkerFinishedEvent;
        public event WorkerHasError WorkerErredEvent;
        public event WorkerCancelled WorkerCancelledEvent;
        public event WorkerStatusChanged WorkerStatusChangedEvent;

        #region work
        private void GetFiles()
        {
            try
            {
                List<string> filesReturned=new List<string>();
                DirectoryInfo dirInfo=new DirectoryInfo(this._Instruction.FolderPath);
                FileInfo[] files = dirInfo.GetFiles("*.*", this._Instruction.SearchOption);
                int fileProcessedCount = 0;
                if(files !=null && files.Length>0)
                {
                    Regex regex=new Regex(this._Instruction.FileNamePattern,RegexOptions.IgnoreCase);
                    foreach(FileInfo file in files)
                    {
                        Match match = regex.Match(file.Name);
                        if(match.Success)
                        {
                            filesReturned.Add(file.FullName);
                        }

                        fileProcessedCount++;
                        if(this.WorkerStatusChangedEvent !=null)
                        {
                            string msg =
                                string.Format("Processng {0}, # {1} of {2}", file.Name, fileProcessedCount, files.Length);
                            int percent = (fileProcessedCount*100)/files.Length;
                            this.WorkerStatusChangedEvent(this._TicketID, this.GetType(), this._Instruction,
                                this.WorkflowName, this.ComponentName, msg,
                                                          percent);
                        }
                    }
                }
                this._Output = new FileLoopOutput(this._Instruction.OwnerComponentID, this._TicketID, filesReturned);
                    
                if(this.WorkerFinishedEvent !=null)
                {
                    this.WorkerFinishedEvent(this._TicketID, this.GetType(), this._Instruction, this._Output);
                }
            }
            catch(Exception ex)
            {
                if(this.WorkerErredEvent !=null)
                {
                    this.WorkerErredEvent(this._TicketID, this.GetType(), this._Instruction, ex.ToString(),true);
                }
            }
        }
        #endregion
    }
}
